
package servlet;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.ContactUtil;
import util.MiscUtil;



/**
 * Servlet implementation class EmailServlet
 */
@WebServlet(urlPatterns = { "/Contact", "/contact", "/ContactServlet", "/contactServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class ContactsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	/**
	 * Default constructor.
	 */
	public ContactsServlet() {
		// TODO Auto-generated constructor stub
		
		
	}


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String strMode = MiscUtil.getStringUrlParam(request, "mode");
		
		String strEmail = "buzzsystememail@gmail.com";
		String strPassword = "buzzsystemtest";
		
		if (strMode.equalsIgnoreCase("delete"))
		{
			String strContactId = MiscUtil.getStringUrlParam(request, "id");
			if (strContactId != "")
			{
				ContactUtil.delete(strEmail, strPassword, strContactId);
				response.sendRedirect("contactList.jsp");
			}
		}
		else if (strMode.equalsIgnoreCase("edit"))
		{
			String strContactId = MiscUtil.getStringUrlParam(request, "id");
			if (strContactId != "")
			{
				ContactUtil.update(strEmail, strPassword, strContactId);
				response.sendRedirect("contactList.jsp");
			}
			
		}
	}

//	private String createXMLEmailString(Message[] msgs, Folder folder) {
//		try {
//			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
//			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
//			Document doc = docBuilder.newDocument();
//			Element root = doc.createElement("EmailList");// EmailList
//			doc.appendChild(root);
//
//			POP3Folder popFolder = (POP3Folder) folder;
//
//			for (int i = 0; i < msgs.length; i++) {
//				Element uniqueId = doc.createElement("UniqueID");
//				String strId = popFolder.getUID(msgs[i]);
//				if (checkForCachingExistence("buzzsystememail", strId) == true)
//				{
//					continue;
//				}
//
//				Element emailItem = doc.createElement("EmailItem");// EmailItem
//				emailItem.setAttribute("WasRead", "false");
//				root.appendChild(emailItem);
//				
//				Element subject = doc.createElement("Subject");// Subject
//				subject.setTextContent(msgs[i].getSubject());
//				emailItem.appendChild(subject);
//
//				Element sentDate = doc.createElement("SentDate");
//				sentDate.setTextContent(util.DateTimeUtil.getDateTimeString(msgs[i].getSentDate()));
//				emailItem.appendChild(sentDate);
//
//				Element from = doc.createElement("From");
//				from.setTextContent(getFromListString(msgs[i]));
//				emailItem.appendChild(from);
//
//				Element cc = doc.createElement("CCList");
//				cc.setTextContent(getCCListString(msgs[i]));
//				emailItem.appendChild(cc);
//
//				Element to = doc.createElement("ToList");
//				to.setTextContent(getToListString(msgs[i]));
//				emailItem.appendChild(to);
//
//				uniqueId.setTextContent(strId);
//				emailItem.appendChild(uniqueId);
//				
//				Element content = doc.createElement("EmailContent");
//				
//				try
//				{
//					Multipart parts = (Multipart) msgs[i].getContent();
//					int iPartCount = parts.getCount();
//					for (int j = 0; j < iPartCount; j++) {
//						BodyPart p = parts.getBodyPart(j);
//						Element eBodyPart = doc.createElement("EmailContentPart");// BodyPart
//						String strContentType = p.getContentType();
//						if (strContentType.indexOf("text/html") > -1) {
//							
//							int index = strContentType.indexOf("charset=");
//							String charset = strContentType.substring(index + 8/*length of(charset=)*/);
//							//System.out.println(charset);
//							
//							String strContent = p.getContent().toString();
//	
//	//						if (charset.equalsIgnoreCase("ISO-8859-1"))
//	//						{
//	//							strContent = new String(strContent.getBytes("UTF-8"), "UTF-8");
//	//							System.out.println("changed to utf-8");
//	//						}
//							strContent = strContent.replaceAll("<.?html>|<.?body>", "");
//							eBodyPart.setTextContent(strContent);
//							eBodyPart.setAttribute("PartType", p.getContentType());
//							content.appendChild(eBodyPart);
//						} else {
//							// TODO: get some things else
//							// eBodyPart.setAttribute("type", p.getContentType());
//							// eBodyPart.setTextContent(p.getContent().toString());
//							// content.appendChild(eBodyPart);
//						}
//					}
//				}
//				catch (ClassCastException  ex)
//				{
//					System.out.println("Caching email error: " + ex.toString());
//					continue;
//				}
//				emailItem.appendChild(content);
//				prepareEmailFolders("buzzsystememail");
//				writeXmlNodeToFile(emailItem, getEmailCachingFolder() + "/" + "buzzsystememail", strId + CACHED_EMAIL_FILE_EXTENTION);
//			}
//
//			TransformerFactory transfac = TransformerFactory.newInstance();
//			Transformer trans = transfac.newTransformer();
//			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
//			trans.setOutputProperty(OutputKeys.INDENT, "yes");
//
//			
//			// create string from xml tree
//			StringWriter sw = new StringWriter();
//			StreamResult result = new StreamResult(sw);
//			DOMSource source = new DOMSource(doc);
//			trans.transform(source, result);
//			
//			String xmlString = sw.toString();
//			return xmlString;
//
//		} catch (Exception e) {
//			System.out.println("Error in caching: " + e.toString());
//			return "<EmailList value=\"Error\"/>";
//		}
//	}
	
//	private boolean checkForCachingExistence(String strAccount, String strId)
//	{
//		File file = new File(getEmailCachingFolder() + "/" + strAccount + "/" + strId + CACHED_EMAIL_FILE_EXTENTION);
//		return file.exists();
//	}
//	
//	private void markAsRead(String strAcc, String strEmailId, boolean wasRead)
//	{   
//		try
//		{
//			File file = new File(getEmailCachingFolder() + "/" + strAcc + "/" + strEmailId + CACHED_EMAIL_FILE_EXTENTION);
//			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//			DocumentBuilder db = dbf.newDocumentBuilder();
//			Document doc = db.parse(file);
//			
//			Element root = doc.getDocumentElement();
//			root.setAttribute("WasRead", wasRead ? "true" : "false");
//			
//			writeXmlNodeToFile(root, getEmailCachingFolder() + "/" + "buzzsystememail", strEmailId + CACHED_EMAIL_FILE_EXTENTION);
//			
//		}
//		catch (Exception ex)
//		{
//			System.out.println("Cannot mark" + strEmailId);
//		}
//	}
//	
//	private String readCachedEmails(String strAccount) {
//		//String xmlString = "";
//		try 
//		{
//			StringBuilder builder = new StringBuilder();
//			byte[] buffer = new byte[8096];
//			int byteCount;
//            
//			File folder = new File(getEmailCachingFolder() + "/" + strAccount);
//			File[] files = folder.listFiles();
//		    for (int i = 0; i < files.length; i++) {
//	            FileInputStream fin = new FileInputStream( files[i].getAbsolutePath());
//	            boolean reachEndOfFile = false;
//	            while (reachEndOfFile == false)
//	            {
//	            	byteCount = fin.read(buffer);
//	            	if (byteCount > 0)
//	            	{
//	            		String xmlString = new String(buffer, 0, byteCount, "UTF-8").replaceAll("<\\?xml .*\\?>", "");
//	            		builder.append(xmlString);
//	            	}
//	            	else
//	            	{
//	            		reachEndOfFile = true;
//	            	}
//	            }
//	            fin.close();
//		    }
//			
//			return builder.toString();
//		} 
//		catch (Exception e) 
//		{
//			return "<EmailList value=\"error\"/>";
//		}
//	}
//	
//	private void prepareEmailFolders(String strAccount)
//	{
//		String str = getEmailCachingFolder();
//		File dir = new File(str);
//		try
//		{
//			if (dir.mkdir() == true)
//			{
//				//
//			}
//			else
//			{
//				
//			}
//			dir = new File(str + "/" + strAccount);
//			dir.mkdir();
//		}
//		catch (Exception ex)
//		{
//			System.out.println("Cannot create EmailCaching folder!");
//		}
//	}
//
//	private String getCurrentDir()
//	{
//		String str = this.getServletContext().getRealPath("");
//		return str;
//	}
//	
//	private String getEmailCachingFolder()
//	{
//		return getCurrentDir() + "/" + CACHED_EMAIL_FOLDER;
//	}
//	
//	private void writeXmlNodeToFile(Node node, String path, String strFileName){
//		try
//		{
//			FileOutputStream writer = new FileOutputStream(path + "/" + strFileName);
//		    TransformerFactory tf = TransformerFactory.newInstance();
//		    // identity
//		    Transformer t = tf.newTransformer();
//		    t.setOutputProperty(OutputKeys.INDENT, "yes");
//		    t.transform(new DOMSource(node), new StreamResult(writer));
//		    writer.close();
//		}
//		catch (Exception ex)
//		{
//			System.out.println("Cannot write email to xml file at writeXml()");
//		}
//	}
//
//	String getFromListString(Message msg) {
//		String str = "";
//		try {
//			Address[] adds = msg.getFrom();
//			for (int i = 0; i < adds.length; i++) {
//				str += adds[i].toString();
//			}
//		} catch (Exception e) {
//
//		}
//		return str;
//	}
//
//	String getToListString(Message msg) {
//		String str = "";
//		try {
//			Address[] adds = msg.getRecipients(Message.RecipientType.TO);
//			for (int i = 0; i < adds.length; i++) {
//				str += adds[i].toString();
//			}
//		} catch (Exception e) {
//
//		}
//		return str;
//	}
//
//	String getCCListString(Message msg) {
//		String str = "";
//		String separator = "";
//		try {
//			Address[] adds = msg.getRecipients(Message.RecipientType.CC);
//			for (int i = 0; i < adds.length; i++) {
//				str += separator + adds[i].toString();
//				separator = ", ";
//			}
//		} catch (Exception e) {
//
//		}
//		return str;
//	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

	}

}